<style>
.image {
  width: 100%;
  display: block;
}
</style>
<template>
  <div>
    <avue-crud :option="guardOption" ref="crud" v-model="guardForm" :page="guardPage" :data="guardData" :table-loading="guardLoading" :before-open="beforeOpen" :before-close="beforeClose" @refresh-change="refreshChange" @search-change="searchChange" @current-change="currentChange" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave">
      <template slot="imgPath" slot-scope="scope">
        <el-button @click="showImgPath(scope.row)">查看</el-button>
      </template>
      <template slot="communityId" slot-scope="scope">
        {{scope.row.communityName}}
      </template>
      <template slot="buildingId" slot-scope="scope">
        {{scope.row.buildingName}}
      </template>
      <template slot="unitId" slot-scope="scope ">
        {{scope.row.unitName}}
      </template>
      <template slot="communityIdForm" slot-scope="scope">
        <avue-crud-select v-model="guardForm.communityId" :dic="communityDic" :size="scope.column.size"></avue-crud-select>
      </template>
      <template slot="buildingIdForm" slot-scope="scope">
        <avue-crud-select v-model="guardForm.buildingId" :dic="buildingDic" :size="scope.column.size"></avue-crud-select>
      </template>
      <template slot="unitIdForm" slot-scope="scope ">
        <avue-crud-select v-model="guardForm.unitId" :dic="unitDic" :size="scope.column.size"></avue-crud-select>
      </template>
      <template slot-scope="scope" slot="imgPathForm">
        <el-col :span="24">
          <el-form-item prop="imgPath">
            <el-upload class="upload-demo" action="/entrance-guard/initialQrManage/upload" :on-preview="imgHandlePreview" :on-remove="imgHandleRemove" :before-upload="beforeImgUpload" :file-list="imgList" :headers="uploadHeader" :data="uploadParams" :on-success="imgSuccess" :limit="imgLimit" :on-exceed="imgExceed" :before-remove="beforeRemove" list-type="picture">
              <el-button size="small" type="primary">上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </template>
    </avue-crud>
    <el-dialog title="图片" :visible.sync="imgFormVisible" :close-on-click-modal="false">
      <el-row>
        <el-col v-for="(imgPath,index) in imgListShow" :key="index">
          <el-card :body-style="{padding:'0px'}">
            <img :src="imgPath" class="image" />
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { validatenull } from "@/util/validate";
import { getToken, setToken, removeToken } from "@/util/auth";
import request from "@/router/axios";
import {
  fetchList,
  addObj,
  putObj,
  delObj,
  getImg,
  communityList,
  buildingList,
  unitList,
  getCommunityById,
  getBuildingById,
  getUnitById
} from "@/api/initialqr";
export default {
  name: "initial_qr",
  data() {
    return {
      communityDic: [],
      buildingDic: [],
      unitDic: [],
      imgLimit: 1,
      imgPaths: [],
      imgList: [],
      imgListShow: [],
      imgFormVisible: false,
      uploadParams: { type: "initialqr" },
      uploadHeader: {
        Authorization: "Bearer " + getToken()
      },
      guardForm: {},
      guardSearch: {},
      guardLoading: false,
      guardPage: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10 //每页显示多少条
      },
      guardOption: {
        index: true,
        border: true,
        stripe: true,
        height: "auto",
        calcHeight: 360,
        searchSize: "small",
        indexLabel: "序号",
        column: [
          {
            label: "类型",
            size: "small",
            prop: "type",
            type: "select",
            search: true,
            disabled: true,
            dicData: [
              {
                label: "超级管理员",
                value: "0"
              },
              {
                label: "物业管理员",
                value: "1"
              },
              {
                label: "业主",
                value: "2"
              }
            ],
            rules: [
              {
                required: true,
                message: "请输入类型",
                trigger: "blur"
              }
            ]
          },
          {
            label: "小区",
            size: "small",
            prop: "communityId",
            type: "select",
            disabled: true,
            formsolt: true,
            solt: true
          },
          {
            label: "楼宇",
            size: "small",
            prop: "buildingId",
            type: "select",
            disabled: true,
            formsolt: true,
            solt: true
          },
          {
            label: "单元",
            size: "small",
            prop: "unitId",
            type: "select",
            disabled: true,
            formsolt: true,
            solt: true
          },
          {
            label: "图片",
            size: "small",
            prop: "imgPath",
            align: "center",
            solt: true,
            span: 24,
            formsolt: true,
            disabled: true
          }
        ]
      },
      guardData: []
    };
  },
  created() {
    this.getList();
    this.getCommunityList();
  },
  watch: {
    "guardForm.communityId": function(n, o) {
      if (!validatenull(n) && !validatenull(o)) {
        this.guardForm.buildingId = "";
        this.guardForm.unitId = "";
      }
      if (validatenull(n)) {
        return;
      }
      this.communityChange();
    },
    "guardForm.buildingId": function(n, o) {
      if (!validatenull(n) && !validatenull(o)) {
        this.guardForm.unitId = "";
      }
      if (validatenull(n)) {
        return;
      }
      this.buildingChange();
    }
  },
  methods: {
    getLabelByValue(list, val) {
      let obj;
      list.forEach(ele => {
        if (ele.value == val) {
          obj = ele;
        }
      });
      return obj;
    },
    getCommunityList() {
      communityList().then(response => {
        const data = response.data;
        if (!validatenull(data)) {
          var list = data;
          this.communityDic = [];
          list.forEach(ele => {
            this.communityDic.push({
              label: ele.name,
              value: ele.id
            });
          });
        }
      });
    },
    communityChange() {
      buildingList(this.guardForm.communityId).then(response => {
        const data = response.data;
        if (!validatenull(data)) {
          var list = data;
          this.buildingDic = [];
          list.forEach(ele => {
            this.buildingDic.push({
              label: ele.buildingName,
              value: ele.id
            });
          });
        }
      });
    },
    buildingChange() {
      unitList(this.guardForm.buildingId).then(response => {
        const existUnit = response.data.attributes.existUnit;
        const data = response.data.obj;
        if (!validatenull(data)) {
          var list = data;
          this.unitDic = [];
          if (existUnit == "1") {
            list.forEach(ele => {
              this.unitDic.push({
                label: ele.unitName,
                value: ele.id
              });
            });
          }
        }
      });
    },
    getList(form) {
      this.guardLoading = true;
      fetchList(
        Object.assign({}, form, {
          page: this.guardPage.currentPage,
          limit: this.guardPage.pageSize
        })
      ).then(response => {
        this.guardLoading = false;
        this.guardData = response.data.records;
        this.guardPage.total = response.data.total;
      });
    },
    currentChange(val) {
      this.guardPage.page = val;
      this.getList();
    },
    refreshChange(val) {
      this.getList();
      this.$message({
        showClose: true,
        message: "刷新成功",
        type: "success"
      });
    },
    searchChange(val) {
      this.guardSearch = val;
      this.getList(this.guardSearch);
    },
    beforeClose(done) {
      this.guardForm.communityId = "";
      this.guardForm.buildingId = "";
      this.guardForm.unitId = "";
      this.buildingDic = [];
      this.unitDic = [];
      this.imgPaths = [];
      this.imgList = [];
      done();
    },
    beforeOpen(show) {
      setTimeout(() => {
        if (!validatenull(this.guardForm.imgPath)) {
          this.imgList = [];
          this.imgPaths = this.guardForm.imgPath;
          getImg(this.guardForm.imgPath).then(res => {
            var name = this.guardForm.imgPath.split("/");
            this.imgList.push({
              name: name[1],
              url: `data:image/gif;base64,${res.data}`
            });
          });
        } else {
          this.imgList = [];
        }
        show();
      }, 0);
    },
    rowDel(row, index) {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return delObj(row.id);
        })
        .then(data => {
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          this.getList();
        })
        .catch(function(err) {});
    },
    rowSave(row, done) {
      row.imgPath = this.imgPaths.toString();
      if (validatenull(row.imgPath)) {
        this.$message.warning(`请先上传图片`);
      } else {
        addObj(Object.assign({}, row)).then(data => {
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success"
          });
          this.getList();
          done();
        });
      }
    },
    rowUpdate(row, index, done) {
      row.imgPath = this.imgPaths.toString();
      putObj(row).then(data => {
        this.$message({
          showClose: true,
          message: "修改成功",
          type: "success"
        });
        this.getList();
        done();
      });
    },
    //图片点击事件
    imgHandlePreview: function(file) {},
    //图片删除事件
    imgHandleRemove: function(file, fileList) {
      this.imgPaths = [];
      this.imgList = [];
    },
    //图片上传之前验证格式
    beforeImgUpload: function(file) {
      const type = file.type;
      const flag =
        type == "image/jpeg" ||
        type == "image/gif" ||
        type == "image/png" ||
        type == "image/bmp";
      if (!flag) {
        this.$message.error("只支持上传图片!");
      }
      return flag;
    },
    //图片上传成功后
    imgSuccess: function(response, file, fileList) {
      var path = response.attributes.filepath;
      this.imgPaths.push(path);
    },
    showImgPath(row) {
      this.imgListShow = [];
      getImg(row.imgPath).then(res => {
        this.imgFormVisible = true;
        this.imgListShow.push("data:image/gif;base64," + res.data);
      });
    },
    imgExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除？`);
    }
  }
};
</script>
